// Package middleware
// @File: recover.go
// @Description: 恢复中间件
// @Author: YaoRuiQi
// @Date: 2025/8/23 02:51

package middleware

import (
	"GinStandardTemplate/internal/pkg/codes"
	"GinStandardTemplate/internal/pkg/contextUtils"
	"GinStandardTemplate/internal/pkg/response"
	"GinStandardTemplate/utils/i18n"
	"GinStandardTemplate/utils/logger"
	"io"
	"runtime/debug"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func GinRecovery() gin.HandlerFunc {
	return gin.RecoveryWithWriter(io.Discard, func(c *gin.Context, err interface{}) {
		var log *zap.Logger

		ctx, getReqContextErr := contextUtils.FromContext(c.Request.Context())
		if getReqContextErr != nil {
			log = logger.Logger
		} else {
			log = ctx.Logger
		}

		log.Error("panic recovered",
			zap.Any("error", err),
			zap.String("path", c.Request.URL.Path),
			zap.ByteString("stacktrace", debug.Stack()),
		)

		response.JSONResponse(
			c,
			codes.InternalError.Code(),
			i18n.GetMessage(ctx, codes.InternalError.MessageID(), nil),
			nil,
		)
		c.Abort()
	})
}
